package storage

import (
	"fmt"
	"gitee.com/zr233/bsf/config"
	"gitee.com/zr233/bsf/model"
)

type Collection struct {
	storageMap    map[string]model.Storage
	configManager *config.Manager
	engine        model.Engine
}

func NewCollection(configManager *config.Manager, engine model.Engine) (c *Collection, err error) {
	c = &Collection{configManager: configManager, engine: engine}
	c.storageMap = map[string]model.Storage{}
	return
}

func (c *Collection) AutoConfig(key string, storage model.Storage) (err error) {
	configPtr := storage.GetConfigPtr()
	err = c.configManager.DB.Unmarshal(key, configPtr)
	if err != nil {
		c.engine.Logger().Error(fmt.Sprintf("config [%s] err:\n%s", key, err))
		return err
	}
	err = storage.Open()
	if err != nil {
		c.engine.Logger().Error(fmt.Sprintf("storage [%s] open err:\n%s", key, err))
		return
	}
	c.storageMap[key] = storage

	err = c.configManager.DB.Watch(key, configPtr, func(err error) {
		if err != nil {
			c.engine.Logger().Error(fmt.Sprintf("config [%s] err:\n%s", key, err))
			return
		}

		storage.Close()
		err = storage.Open()
		if err != nil {
			c.engine.Logger().Error(fmt.Sprintf("storage [%s] open err:\n%s", key, err))
		}
	})

	return
}
